const {GlobalData} = require("./DataInit/GlobalData.js");
const notifier = require('node-notifier');
const Process = require("./Tools/ProcessTool.js");
const GitTool = require("./Tools/GitTool.js");
const InputTool = require('./Tools/InputTool.js');
const NotifyTool = require("./Tools/NotifyTool.js");
// 项目的根目录
const ROOT = GlobalData.ROOT;
// 定义一个项目(其实就是)


main()

async function main(){
    let options = {
        "测试（默认分支为release）" : "test",
        "线网（暂时不建议用这个构建，）" : "prd"
    }
    let gitOption = {

    }
    const filterInput = ['test','prd'];


    try {
        console.log('--- 一键编译提交推送 --- ');
        console.log()
        // 初始化选择构建环境
        let type = await InputTool.list('请选择你要构建的环境', Object.keys(options));
        type = options[type];
        // 填写构建发布的分支，测试环境默认均为release
        let branch = type == "test" ? 'release' : 'master';
        // if (!filterInput.some(item=>item == type)) {
        //     branch = await InputTool.input(type == 'test' ? '默认构建分支均为release，回车跳过即可' : '请输入RJReact分支名称：release_2023xxxx') || "release"
        // }
        // 输入需要构建的站点，fe-newweb，fe-sp等
        let env = await InputTool.input("请输入需要编译构建的站点，多个用英文逗号分割，默认fe-newweb") || "fe-newweb"

        // 输入构建提交的commit
        let commit = await InputTool.input("请输入构建提交的Commit") || "buildCode"

        console.log(commit);

        // domain(branch,env)
        processArray(branch,env.split(","),commit)
            .then(() => {
                console.log("--------------------All Process Run finish--------------------")
                const notify = new NotifyTool();
                notify.Alert({title : "构建成功",message: `${env}构建成功`})

            })
            .catch(error => {
                // 处理错误
                console.error(error);
            });


        console.log('--- End --- ');
        console.log()


    } catch (err) {
        console.error('流程错误:', err);
    }
}

function loopDAO(){

}

async function domain(branch,env) {
    // 执行异步操作
    let _env = GlobalData.env(env);
    const process = new Process(`${ROOT}${GlobalData.BASE_ROOT}`);
    const git = new GitTool(`${ROOT}${_env}`);
    const pull = await git.pull(branch);
    await process.asyncRun("npm", ["run", GlobalData.envCommand(_env)]);
    const status = await git.status();
    const add = await git.add();
    const commit = await git.commit("buildCode");
    const push = await git.push("release");
    const notify = new NotifyTool();
    notify.
    Alert({title : "构建成功",message:   `RJReact：${branch}构建到${env}成功`})
}

function asyncOperation(branch,env,commit) {
    return new Promise(async (resolve, reject) => {
        // 执行异步操作
        let _env = GlobalData.env(env);
        // 初始化RJReact进程
        const process = new Process(`${ROOT}${GlobalData.BASE_ROOT}`);
        const git = new GitTool(`${ROOT}${_env}`);
        const checkout = await git.checkout(branch);
        await process.asyncRun("npm", ["run", GlobalData.envCommand(_env)]);
        const status = await git.status();
        if(status.indexOf("error")){

        }
        const add = await git.add();
        const commitMessage = await git.commit(commit);
        const push = await git.push(branch);
        const notify = new NotifyTool();
        notify.Alert({title : "构建成功",message:   `RJReact：${branch}构建到${env}成功`});
        resolve();
    });
}

async function processArray(branch,items,commit) {
    for (let env of items) {
        try {
            console.log();
            console.log();
            console.log(`-------------------------------------${env} run Start-------------------------------------`);
            // 等待异步操作完成
            await asyncOperation(branch,env,commit);
            console.log(`-------------------------------------${env} run End-------------------------------------`);
            console.log();
            console.log();
        } catch (error) {
            // 处理错误
        }
    }
}




